<template>
  <ContentWrap class="chem-record-wrap">

    <!-- 表格 -->
    <el-table
      :data="form.table"
      border
      class="chem-table"
      stripe
      :span-method="arraySpanMethod"
    >
      <el-table-column align="center" label="工作场所" prop="workplace" width="100">
        <template #default="{ row }">
          <el-input v-model="row.workplace" placeholder="" @change="handleTableDataChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="检测岗位" prop="detectionPost" width="100">
        <template #default="{ row }">
          <el-input v-model="row.detectionPost" placeholder="" @change="handleTableDataChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="检测项目" prop="item">
        <template #default="{ row }">
          <el-input v-model="row.item" placeholder="" @change="handleTableDataChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="对象/采样点及时机" prop="samplePoint">
        <template #default="{ row }">
          <el-input v-model="row.samplePoint" placeholder="" @change="handleTableDataChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="样品编号" prop="sampleNo">
        <template #default="{ row }">
          <el-input v-model="row.sampleNo" placeholder="" @change="handleTableDataChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="原始结果" prop="result" width="80">
        <el-table-column align="center" label="Cᵢ(mg/m³)" prop="result" width="80">
          <template #default="{ row }">
            <el-input v-model="row.result" placeholder="" @change="handleTableDataChange" />
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column align="center" label="代表接触时间" prop="contactTime" width="90">
        <el-table-column align="center" label="Tᵢ(h)" prop="contactTime" width="90">
          <template #default="{ row }">
            <el-input v-model="row.contactTime" placeholder="" @change="handleTableDataChange" />
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column align="center" label="日工作时间" prop="workHours" width="90">
        <el-table-column align="center" label="T_d(h)" prop="workHours" width="90">
          <template #default="{ row }">
            <el-input v-model="row.workHours" placeholder="" @change="handleTableDataChange" />
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column align="center" label="周工作天数" prop="workDays" width="90">
        <el-table-column align="center" label="W(d)" prop="workDays" width="90">
          <template #default="{ row }">
            <el-input v-model="row.workDays" placeholder="" @change="handleTableDataChange" />
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column align="center" label="周工作时间" prop="weeklyWorkHours" width="90">
        <el-table-column align="center" label="T_w(h)" prop="weeklyWorkHours" width="90">
          <template #default="{ row }">
            <el-input
              v-model="row.weeklyWorkHours"
              placeholder=""
              readonly
              @change="handleTableDataChange"
            />
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column align="center" label="C_TWA" prop="ctwa" width="90">
        <el-table-column align="center" label="(mg/m³)" prop="ctwa" width="90">
          <template #default="{ row }">
            <el-input v-model="row.ctwa" placeholder="" readonly />
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column align="center" label="计算公式" prop="ctwaFormula" width="60">
        <template #default="{ row }">
          <el-input v-model="row.ctwaFormula" placeholder="" readonly />
        </template>
      </el-table-column>
      <el-table-column align="center" label="PC-TWA" prop="pcTwa" width="90">
        <el-table-column align="center" label="(mg/m³)" prop="pcTwa" width="90">
          <template #default="{ row }">
            <el-input v-model="row.pcTwa" placeholder="" @change="handleTableDataChange" />
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column align="center" label="PC-TWAa" prop="pcTwaa" width="90">
        <el-table-column align="center" label="(mg/m³)" prop="pcTwaa" width="90">
          <template #default="{ row }">
            <el-input v-model="row.pcTwaa" placeholder="" @change="handleTableDataChange" />
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column align="center" label="RF" prop="rf" width="60">
        <template #default="{ row }">
          <el-input v-model="row.rf" placeholder="" readonly />
        </template>
      </el-table-column>
      <el-table-column align="center" label="计算公式" prop="rfFormula" width="60">
        <template #default="{ row }">
          <el-input v-model="row.rfFormula" placeholder="" readonly />
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue'
import ContentWrap from '@/components/ContentWrap/src/ContentWrap.vue'

// 定义表格行数据类型
interface CtwaTableRow {
  workplace: string // 工作场所
  detectionPost: string // 检测岗位
  item: string // 检测项目
  samplePoint: string // 对象/采样点及时机
  sampleNo: string // 样品编号
  result: string // 原始结果 Cᵢ (mg/m³)
  contactTime: string // 代表接触时间 Tᵢ (h)
  workHours: string // 日工作时间 T_d (h)
  workDays: string // 周工作天数 W (d)
  weeklyWorkHours: string // 周工作时间 T_w (h)
  ctwa: string // C_TWA (mg/m³) - 只读计算字段
  ctwaFormula: string // 计算公式 - 只读字段
  pcTwa: string // PC-TWA (mg/m³)
  pcTwaa: string // PC-TWAa (mg/m³)
  rf: string // RF - 只读计算字段
  rfFormula: string // 计算公式 - 只读字段
}

// 定义表单数据类型
interface CtwaFormData {
  type: string // 检测类别
  table: CtwaTableRow[] // 表格数据
}

// 新增type和formData prop
const props = defineProps<{
  formData?: any
}>()

const emit = defineEmits(['change'])

defineOptions({ name: 'CtwaDataProcessing' })

const emitChange = () => {
  emit('change', { ...form.value })
}

// 监听表格数据变化，自动计算
const handleTableDataChange = () => {
  if (!form.value?.table) return
  form.value.table.forEach((row: any) => {
    const workHoursNum = parseFloat(row.workHours) || 0
    const workDaysNum = parseFloat(row.workDays) || 0

    if (workHoursNum && workDaysNum) {
      const weekly = workHoursNum * workDaysNum
      row.weeklyWorkHours = String(Number.isFinite(weekly) ? parseFloat(weekly.toFixed(2)) : '')
    } else {
      row.weeklyWorkHours = ''
    }
  })
  emitChange()
}

// 响应式form，并与父组件传入的formData合并
const form = ref<CtwaFormData>({
  type: '',
  table: []
})

// 监听父组件formData变化，重新合并为本地form
watch(
  () => props.formData,
  (val) => {
    if (val) {
      form.value.table = val.ctwa
      form.value.type = val.type
      handleTableDataChange()
      console.log('111', JSON.stringify(form.value))
    }
  },
  { immediate: true }
)

// 暴露数据与方法给父组件
defineExpose({
  form
})

// 合并单元格方法
const arraySpanMethod = ({ row, column, rowIndex, columnIndex }: any) => {
  if (!form.value.table || form.value.table.length === 0) {
    return [1, 1]
  }

  // 仅对前两列分组合并：第1列自身；第2列第1+2
  if (columnIndex === 0 || columnIndex === 1) {
    const getGroupKey = (r: any) => {
      if (columnIndex === 0) return `${r.workplace}`
      return `${r.workplace}__${r.detectionPost}`
    }

    const currentKey = getGroupKey(form.value.table[rowIndex])

    if (rowIndex > 0) {
      const prevKey = getGroupKey(form.value.table[rowIndex - 1])
      if (prevKey === currentKey) {
        return [0, 0]
      }
    }

    let rowspan = 1
    for (let i = rowIndex + 1; i < form.value.table.length; i++) {
      const nextKey = getGroupKey(form.value.table[i])
      if (nextKey === currentKey) {
        rowspan++
      } else {
        break
      }
    }
    return [rowspan, 1]
  }

  return [1, 1]
}

onMounted(() => {})
</script>

<style lang="scss" scoped>
.chem-title {
  font-size: 26px;
  font-weight: 600;
  color: #222;
  flex-grow: 1;
  text-align: center;
}

.chem-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 0 0 24px 0;
  padding: 16px 0 16px 0;
  border-bottom: 1.5px solid #409eff;
  font-size: 20px;
  font-weight: 600;
  color: #409eff;
  background: none;
  border-radius: 0;
  box-shadow: none;
  letter-spacing: 1px;
}

.chem-form {
  background: none;
  box-shadow: none;
  border-radius: 0;
  margin-bottom: 0;

  :deep(.el-input__inner) {
    border-radius: 0 !important;
    box-shadow: none !important;
  }

  :deep(.el-form-item__label) {
    white-space: nowrap;
  }
}

.chem-btns {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  align-items: center;
  margin-top: 0;
}

.chem-table {
  margin-top: 18px;
  --el-table-border-radius: 0 !important;
  --el-table-header-bg-color: #f7f8fa;
  --el-table-border-color: #e5e6eb;
  box-shadow: none !important;
  border-radius: 0 !important;

  :deep(.el-table__header th) {
    background: #f7f8fa !important;
    font-weight: 600;
    font-size: 14px;
    border-radius: 0 !important;
    padding: 8px 0 !important;

    .cell {
      padding-left: 0px !important;
      padding-right: 0px !important;
    }
  }

  // 设置表格行高
  :deep(.el-table__body td) {
    border-radius: 0 !important;

    font-size: 14px;
    padding: 0 !important;
    // 列和单元格的边距
    .cell {
      padding: 0px 0px;
    }
  }

  // 去掉输入框边框
  :deep(.el-input__wrapper) {
    border-radius: 0 !important;
    box-shadow: none !important;
  }

  // 针对下拉选择框的所有相关元素去掉边框
  :deep(.el-select__wrapper) {
    border: none !important;
    box-shadow: none !important;
  }
}

.input-with-unit {
  position: relative;
}

.unit-text {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: #909399;
  font-size: 14px;
  pointer-events: none;
  z-index: 1;
}
</style>
